/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.app.storage.file;

import java.io.File;
import java.net.URI;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import org.atomojo.app.Storage;
import org.atomojo.app.StorageFactory;
import org.atomojo.app.db.DB;
import org.infoset.xml.DocumentLoader;
import org.infoset.xml.sax.SAXDocumentLoader;
import org.restlet.Context;
import org.restlet.data.Protocol;

/**
 *
 * @author alex
 */
public class FileStorageFactory implements StorageFactory {

   static Set<Protocol> protocols = new HashSet<Protocol>();
   static {
      protocols.add(Protocol.FILE);
   }
   Map<String,FileStorage> cache;
   DocumentLoader loader;
   Context context;
   public FileStorageFactory() {
      cache = new TreeMap<String,FileStorage>();
      loader = new SAXDocumentLoader();
   }

   public void init(Context context) {
      this.context = context;
   }
   
   public Set<Protocol> getStorageProtocols() {
      return protocols;
   }

   public Storage getStorage(DB db) 
      throws Exception
   {
      FileStorage storage = cache.get(db.getName());
      if (storage==null) {
         File dbDir = db.getDatabaseDir();
         File contentDir = new File(dbDir,"content");
         Properties configuration = db.getConfiguration();
         String contentS = configuration.getProperty("content");
         if (contentS!=null) {
            String baseS = configuration.getProperty("base-uri");
            URI baseURI = baseS==null ? db.getDatabaseDir().toURI() : URI.create(baseS);
            URI contentRef = baseURI.resolve(contentS==null ? "content" : contentS);
            if (!contentRef.getScheme().equals("file")) {
               throw new IllegalArgumentException("A non-file URI is not allowed for file content storage: "+contentRef);
            }
            contentDir = new File(contentRef.getSchemeSpecificPart());
         }
         
         storage = new FileStorage(loader,db,contentDir);
         cache.put(db.getName(),storage);
         storage.init(context);
      }
      return storage;
   }
}
